﻿using IOP.SgrA;
using IOP.SgrA.ECS;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;

namespace VkSample82
{
    public class EarthSystem : ComponentSystem
    {
        private readonly ILogger<EarthSystem> _Logger;
        private float earthAngle;

        private readonly Vector3 Y = new Vector3(0, 1, 0);

        public EarthSystem(ILogger<EarthSystem> logger)
        {
            _Logger = logger;
        }

        public override void Initialization()
        {
            ContextManager.Foreach<EarthGroup>((group) => 
            {
                group.Transform.Scale = new Vector3(3, 3, 3);
                Context context = ContextManager.GetContext(group.Entity);
                ref MVPMatrix mvp = ref context.GetMVPMatrix();
                mvp.ModelMatrix = Matrix4x4.CreateScale(group.Transform.Scale);
                return group;
            });
        }

        public override void Update(TimeSpan lastStamp)
        {
            try
            {
                earthAngle += 0.4f;
                if (earthAngle >= 360) earthAngle = 0;
                ContextManager.Foreach<EarthGroup>((group) =>
                {
                    Context context = ContextManager.GetContext(group.Entity);
                    ref MVPMatrix mvp = ref context.GetMVPMatrix();
                    mvp.ModelMatrix = Matrix4x4.CreateFromAxisAngle(Y, earthAngle * MathF.PI / 180.0f) * Matrix4x4.CreateScale(group.Transform.Scale);
                    context.PushToRenderGroup();
                });
            }
            catch (Exception e)
            {
                _Logger.LogInformation(e.Message);
            }
        }
    }

    struct EarthGroup
    {
        public Entity Entity;
        public EarthComponent Earth;
        public TransformComponent Transform;
    }
}
